from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View

from users.forms import UserForm


# Create your views here.
class RegisterView(View):
    def get(self, request):
        user = UserForm()
        return render(request, 'function/register.html', {'form': user})

    def post(self, request):
        user = UserForm(request.POST)
        message = ''
        if user.is_valid():
            username = user.cleaned_data.get('username')
            password = user.cleaned_data.get('password')
            user = User(username=username)
            user.set_password(password)
            try:
                user.save()
            except IntegrityError:
                message = '用户名已存在'
            else:
                message = '注册成功'
        return render(request, 'function/register.html', {'message': message})


class LoginView(View):
    def get(self, request):
        user = UserForm()
        return render(request, 'function/login.html', {'form': user})

    def post(self, request, *args, **kwargs):
        user = UserForm(request.POST)
        message = ''
        if user.is_valid():
            username = user.cleaned_data.get('username')
            password = user.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url)
                return redirect('homepage')
            else:
                message = '用户名或密码错误'
        return render(request, 'function/login.html', {'user': user, 'message': message})


def LogoutView(request, **kwargs):
    logout(request)
    return redirect('login')
